import 'dart:io';
import 'dart:convert';
import 'package:csv/csv.dart';
import 'package:path/path.dart' as path;

class CsvData {
  final String fileName;
  final List<List<String>> data;
  final List<String> headers;

  CsvData({
    required this.fileName,
    required this.data,
    required this.headers,
  });
}

class CsvReader {
  /// 读取CSV文件
  static Future<List<CsvData>> readCsvFile(String filePath) async {
    try {
      final file = File(filePath);
      if (!await file.exists()) {
        throw Exception('文件不存在: $filePath');
      }

      // 读取文件内容
      String fileContent = await file.readAsString(encoding: utf8);

      // 解析CSV内容
      List<List<dynamic>> csvTable = const CsvToListConverter(eol: '\n').convert(fileContent);

      if (csvTable.isEmpty) {
        throw Exception('CSV文件为空或格式错误');
      }

      List<CsvData> csvDataList = [];
      List<String> headers = [];
      List<List<String>> data = [];

      // 获取表头（第一行）
      if (csvTable.isNotEmpty) {
        for (var cell in csvTable.first) {
          headers.add(cell?.toString() ?? '');
        }
      }

      // 获取数据行（从第二行开始）
      for (int row = 1; row < csvTable.length; row++) {
        List<String> rowData = [];
        for (var cell in csvTable[row]) {
          rowData.add(cell?.toString() ?? '');
        }
        // 只添加非空行
        if (rowData.any((cell) => cell.isNotEmpty)) {
          data.add(rowData);
        }
      }

      // 使用文件名作为"工作表"名称
      String fileName = path.basenameWithoutExtension(filePath);
      
      csvDataList.add(CsvData(
        fileName: fileName,
        data: data,
        headers: headers,
      ));

      return csvDataList;
    } catch (e) {
      throw Exception('读取CSV文件失败: $e');
    }
  }

  static List<List<String?>> findHttp(CsvData sheet, String appName) {
    // 获取到http
    int findColumnCode = -1;
    // 获取列号 以获取域名
    for (int i = 0; i < sheet.headers.length; i++) {
      if(sheet.headers[i].contains("新正式域名")) {
        findColumnCode = i;
        break;
      }
    }
    List<int> findRowCodeList = [];
    // 获取行号以获取域名
    for (int i = 0; i < sheet.data.length; i++) {
      if(sheet.data[i][0].toLowerCase().contains(appName.toLowerCase())) {
        findRowCodeList.add(i);
      }
    }
    List<List<String?>> result = [];
    if (findRowCodeList != -1 && findRowCodeList.length > 0) {
      for (int i = 0; i < findRowCodeList.length; i++) {
        List<String?> resultCell = [];
        resultCell.addAll(sheet.data[findRowCodeList[i]][findColumnCode].split("\n"));
        result.add(resultCell);
      }
    }
    return result;
  }
}

// 为了保持向后兼容性，添加别名
typedef ExcelData = CsvData;
typedef ExcelReader = CsvReader;